use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(OrderFees::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(OrderFees::Id)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(OrderFees::OrderId).string().not_null())
                    .col(ColumnDef::new(OrderFees::Code).string().not_null())
                    .col(
                        ColumnDef::new(OrderFees::Value)
                            .decimal_len(8, 2)
                            .not_null(),
                    )
                    .col(ColumnDef::new(OrderFees::Title).string().not_null())
                    .col(ColumnDef::new(OrderFees::Reference).json())
                    .col(
                        ColumnDef::new(OrderFees::CreatedAt)
                            .timestamp_with_time_zone()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(OrderFees::UpdatedAt)
                            .timestamp_with_time_zone()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_order_fees_order_id")
                            .from(OrderFees::Table, OrderFees::OrderId)
                            .to(Orders::Table, Orders::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(OrderFees::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum OrderFees {
    Table,
    Id,
    OrderId,
    Code,
    Value,
    Title,
    Reference,
    CreatedAt,
    UpdatedAt,
}

#[derive(DeriveIden)]
enum Orders {
    Table,
    Id,
}
